package com.qin.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qin.entity.OrderBook;
import com.qin.entity.User;
import com.qin.service.OrderService;
import com.qin.service.impl.OrderServiceImpl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;

/**
 * 处理购买图书，生成订单
 */
@WebServlet("/insertorder")
public class InsertOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private OrderService orderService = new OrderServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 从请求域中拿到图书信息和User
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		
		String parameter = request.getParameter("order");
		// 转成JSON数组
		JSONArray parseArray = JSONUtil.parseArray(parameter);
		// JSON数组转成List
		List<OrderBook> list = JSONUtil.toList(parseArray, OrderBook.class);
		
		StaticLog.debug("要插入的订单图书：{}", list);
		
		if(list != null && list.size() > 0) {
			// 开启事务，批量插入订单图书
			Long insertOrderBeforOrderBookByTx = orderService.insertOrderBeforOrderBookByTx(user, list);
			
			if(insertOrderBeforOrderBookByTx != null) {
				// 插入完成后，返回信息
				response.getWriter().print(insertOrderBeforOrderBookByTx);
				return;
			}
			
		}
		response.getWriter().print(false);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
